<template>
  <div class="consumption-records-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>我的消费记录</h2>
      <el-button @click="refreshData" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="选择支付方式" clearable>
            <el-option label="余额支付" value="BALANCE" />
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="微信支付" value="WECHAT" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
            <el-option label="处理中" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="套餐名称">
          <el-input v-model="searchForm.packageName" placeholder="输入套餐名称" clearable />
        </el-form-item>
        
        <el-form-item label="消费时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchRecords" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-card" v-if="statistics">
      <template #header>
        <div class="card-header">
          <el-icon><DataAnalysis /></el-icon>
          <span>消费统计</span>
        </div>
      </template>
      
      <div class="statistics-content">
        <div class="stat-item">
          <div class="stat-label">累计消费金额</div>
          <div class="stat-value total">¥{{ statistics.totalAmount || '0.00' }}</div>
        </div>
      </div>
    </el-card>

    <!-- 消费记录表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>消费记录列表</span>
          <span class="record-count">共 {{ pagination.total }} 条记录</span>
        </div>
      </template>
      
      <el-table 
        :data="tableData" 
        :loading="loading" 
        class="record-table"
        stripe
        border
      >
        <el-table-column prop="id" label="记录ID" width="80" />
        
        <el-table-column prop="orderNo" label="订单号" min-width="180">
          <template #default="{ row }">
            <el-button type="text" @click="copyToClipboard(row.orderNo)">
              {{ row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="packageName" label="套餐名称" min-width="120" />
        
        <el-table-column prop="storeManagerName" label="店长" width="100" />
        
        <el-table-column prop="consumeAmount" label="消费金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.consumeAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            {{ getPaymentMethodName(row.paymentMethod) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.status)"
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="消费时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="消费记录详情" width="600px">
      <div v-if="selectedRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedRecord.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="套餐名称">{{ selectedRecord.packageName }}</el-descriptions-item>
          <el-descriptions-item label="店长">{{ selectedRecord.storeManagerName }}</el-descriptions-item>
          <el-descriptions-item label="消费金额">
            <span class="amount-text">¥{{ selectedRecord.consumeAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ getPaymentMethodName(selectedRecord.paymentMethod) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedRecord.status)">
              {{ getStatusName(selectedRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="消费时间">{{ formatDateTime(selectedRecord.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ selectedRecord.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Search, DataAnalysis } from '@element-plus/icons-vue'
import { 
  getMyConsumptionRecordPage, 
  getMyConsumptionStatistics 
} from '@/api/consumptionRecord'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const statistics = ref(null)
const detailDialogVisible = ref(false)
const selectedRecord = ref(null)

// 搜索表单
const searchForm = reactive({
  paymentMethod: '',
  status: null,
  packageName: '',
  dateRange: null
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 获取消费记录数据
const fetchData = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size
    }
    
    // 添加搜索条件
    if (searchForm.paymentMethod) {
      params.paymentMethod = searchForm.paymentMethod
    }
    if (searchForm.status !== null) {
      params.status = searchForm.status
    }
    if (searchForm.packageName) {
      params.packageName = searchForm.packageName
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }
    
    const response = await getMyConsumptionRecordPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取消费记录失败')
    }
  } catch (error) {
    console.error('获取消费记录失败:', error)
    ElMessage.error('获取消费记录失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const fetchStatistics = async () => {
  try {
    const response = await getMyConsumptionStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 搜索记录
const searchRecords = () => {
  pagination.page = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    paymentMethod: '',
    status: null,
    packageName: '',
    dateRange: null
  })
  pagination.page = 1
  fetchData()
}

// 刷新数据
const refreshData = () => {
  fetchData()
  fetchStatistics()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchData()
}

// 查看详情
const viewDetail = (record) => {
  selectedRecord.value = record
  detailDialogVisible.value = true
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  switch (method) {
    case 'BALANCE': return '余额支付'
    case 'ALIPAY': return '支付宝'
    case 'WECHAT': return '微信支付'
    default: return method || '未知'
  }
}

// 获取状态名称
const getStatusName = (status) => {
  switch (status) {
    case 1: return '成功'
    case 0: return '失败'
    case 2: return '处理中'
    default: return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    case 2: return 'warning'
    default: return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('订单号已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
  fetchStatistics()
})
</script>

<style scoped>
.consumption-records-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.statistics-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.statistics-content {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.total {
  color: #f56c6c;
}

.table-card {
  margin-bottom: 20px;
}

.record-count {
  color: #666;
  font-size: 14px;
}

.record-table {
  width: 100%;
}

.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-content {
  padding: 20px 0;
}
</style> 